import Mock from 'mockjs'

function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) return {}
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}'
  )
}

let List = []
const count = 200

for (let i = 0; i < count; i++) {
  List.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      age: Mock.Random.integer(18, 60),
      sex: Mock.Random.integer(0, 1),
      birth: Mock.Random.date('yyyy-MM-dd'),
      addr: Mock.mock('@province') + ' ' + Mock.mock('@city') + ' ' + Mock.mock('@county(true)')
    })
  )
}

export default {
  // 获取用户列表
  getUserList: config => {
    const { name, page = 1, limit = 20 } = param2Obj(config.url)

    const mockList = List.filter(user => {
      if (name && user.name.indexOf(name) === -1 && user.addr.indexOf(name) === -1) return false
      return true
    })

    const pageList = mockList.filter((item, index) => {
      return index < limit * page && index >= limit * (page - 1)
    })

    return {
      code: 20000,
      count: mockList.length,
      list: pageList
    }
  },

  // 添加用户
  addUser: config => {
    const { name, addr, age, birth, sex } = JSON.parse(config.body)
    List.unshift(
      Mock.mock({
        id: Mock.Random.guid(),
        name,
        addr,
        age,
        birth,
        sex
      })
    )
    return {
      code: 20000,
      data: { message: '添加成功' }
    }
  },

  // 删除用户
  deleteUser: config => {
    const { id } = JSON.parse(config.body)
    const index = List.findIndex(item => item.id === id)
    if (index !== -1) {
      List.splice(index, 1)
      return {
        code: 20000,
        data: { message: '删除成功' }
      }
    } else {
      return {
        code: 40004,
        data: { message: '用户未找到' }
      }
    }
  },

  // 编辑用户
  editUser: config => {
    const { id, name, addr, age, birth, sex } = JSON.parse(config.body)
    const user = List.find(item => item.id === id)
    if (user) {
      user.name = name
      user.addr = addr
      user.age = age
      user.birth = birth
      user.sex = sex
      return {
        code: 20000,
        data: { message: '修改成功' }
      }
    } else {
      return {
        code: 40004,
        data: { message: '用户未找到' }
      }
    }
  }
}
